package com.jiaanpei.frameproject.app;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.util.Log;
import com.github.yuweiguocn.library.greendao.MigrationHelper;
import com.jiaanpei.frameproject.BuildConfig;
import com.jiaanpei.frameproject.gen.DaoMaster;
import com.jiaanpei.frameproject.gen.DaoSession;
import com.jiaanpei.frameproject.manage.MySQLiteOpenHelper;
import com.jiaanpei.frameproject.manage.UmengEvents;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.vise.log.ViseLog;
import com.vise.log.inner.DefaultTree;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.Map;

import imageloader.libin.com.images.config.SingleConfig;
import imageloader.libin.com.images.loader.ImageLoader;

public class AppApplication extends Application {
    public static final String UPDATE_STATUS_ACTION = "com.piccfs.jiaanpei.action.UPDATE_STATUS";
    public  static AppApplication instance;
    private MySQLiteOpenHelper devOpenHelper;
    private Handler handler;
    private SQLiteDatabase db;
    public static final String TAG = "AppApplication";
    private DaoMaster daoMaster;

    private DaoSession daoSession;
    public static synchronized AppApplication getInstance(){
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance=this;
        initViseLog();
        initDataBase();
        initUmeng();
        ImageLoader.init(getApplicationContext());
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);

        ImageLoader.trimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

        ImageLoader.clearAllMemoryCaches();
    }
    private void initUmeng() {
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);//BuildConfig.isdev
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE,
                Constants.UmengKey);
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.MANUAL);
//        MobclickAgent.openActivityDurationTrack(false);
        initUpush();
    }
    private void initViseLog(){
        ViseLog.getLogConfig()
                .configAllowLog(true)//是否输出日志
                .configShowBorders(true)//是否排版显示
                .configTagPrefix("ViseLog")//设置标签前缀
                .configFormatTag("%d{HH:mm:ss:SSS} %t %c{-5}")//个性化设置标签，默认显示包名
                .configLevel(Log.VERBOSE);//设置日志最小输出级别，默认Log.VERBOSE
        ViseLog.plant(new DefaultTree());//添加打印日志信息到Logcat的树
    }

    private void initDataBase() {
        // do this once, for example in your Application class
        MigrationHelper.DEBUG = true;
        devOpenHelper = new MySQLiteOpenHelper(this,new StringBuilder().append(Constants.AppName).append("-db").toString() , null);
        db = devOpenHelper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        QueryBuilder.LOG_SQL = true;
        // 输出带有具体数值的sql日志
        QueryBuilder.LOG_VALUES = true;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    private void initUpush() {
        final PushAgent mPushAgent = PushAgent.getInstance(this);
        handler = new Handler(getMainLooper());

        //sdk开启通知声音
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        mPushAgent.setDisplayNotificationNumber(10);
        // sdk关闭通知声音
        // mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // 通知声音由服务端控制
        // mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);

        // mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);

        UmengMessageHandler messageHandler = new UmengMessageHandler() {

            /**
             * 通知的回调方法（通知送达时会回调）
             */
//            @Override
            public void dealWithNotificationMessage(Context context, UMessage msg) {
                //调用super，会展示通知，不调用super，则不展示通知。
                super.dealWithNotificationMessage(context, msg);
                UmengEvents.pushReceiveMsg(context,"pushReceiveMsg");
            }
//
//            /**
//             * 自定义消息的回调方法
//             */
//            @Override
//            public void dealWithCustomMessage(final Context context, final UMessage msg) {
//
//                handler.post(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        // TODO Auto-generated method stub
//                        // 对自定义消息的处理方式，点击或者忽略
//                        boolean isClickOrDismissed = true;
//                        if (isClickOrDismissed) {
//                            //自定义消息的点击统计
//                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
//                        } else {
//                            //自定义消息的忽略统计
//                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
//                        }
////                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
//                    }
//                });
//            }

            /**
             * 自定义通知栏样式的回调方法
             */
            @Override
            public Notification getNotification(Context context, UMessage msg) {
                switch (msg.builder_id) {
                    case 1:
                        return super.getNotification(context, msg);
                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        /**
         * 自定义行为的回调处理，参考文档：高级功能-通知的展示及提醒-自定义通知打开动作
         * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {

            @Override
            public void launchApp(Context context, UMessage msg) {
                super.launchApp(context, msg);


                UmengEvents.pushOpenMsg(context,"pushOpenMsg");
                if(msg!=null){
                    Map<String, String> extra = msg.extra;
                    if(extra!=null&&extra.size()>0){
                        String actionType = extra.get("actionType");

                    }
                }


            }

            @Override
            public void openUrl(Context context, UMessage msg) {
                super.openUrl(context, msg);
            }

            @Override
            public void openActivity(Context context, UMessage msg) {
                super.openActivity(context, msg);
            }

            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
//                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();


            }
        };
        //使用自定义的NotificationHandler
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        //注册推送服务 每次调用register都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                Log.i(TAG, "device token: " + deviceToken);
                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));

            }

            @Override
            public void onFailure(String s, String s1) {
                Log.i(TAG, "register failed: " + s + " " + s1);
                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));
            }
        });



//        mPushAgent.getTagManager().addTags(new TagManager.TCallBack() {
//            @Override
//            public void onMessage(final boolean isSuccess, final ITagManager.Result result) {
//                //isSuccess表示操作是否成功
//                Log.i("isSuccess",isSuccess+"");
//            }
//        }, SpUtil.getString(getApplicationContext(), Constants.USERNAME, ""));



        //使用完全自定义处理
        //mPushAgent.setPushIntentServiceClass(UmengNotificationService.class);

        //小米通道
//        MiPushRegistar.register(this, "2882303761517836212", "5231783678212");
//        //华为通道
//        HuaWeiRegister.register(this);
//        //魅族通道
//        MeizuRegister.register(this, "114628", "51da96ddfbd843f185057760f67d4176");

    }
}
